package com.pdd.mall.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pdd.mall.common.api.CommonResult;
import com.pdd.mall.dto.OrderCreateParam;
import com.pdd.mall.entity.Order;
import com.pdd.mall.entity.OrderItem;
import com.pdd.mall.entity.User;
import com.pdd.mall.service.OrderService;
import com.pdd.mall.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单控制器
 */
@RestController
@RequestMapping("/user/orders")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserService userService;

    @GetMapping
    public CommonResult<Page<Order>> getOrderList(
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        Long userId = getCurrentUserId();
        Page<Order> orderList = orderService.getOrderList(userId, status, pageNum, pageSize);
        return CommonResult.success(orderList);
    }

    @GetMapping("/{orderNo}")
    public CommonResult<Map<String, Object>> getOrderDetail(@PathVariable String orderNo) {
        Long userId = getCurrentUserId();
        Order order = orderService.getOrderDetail(orderNo, userId);
        if (order == null) {
            return CommonResult.notFound("订单不存在");
        }

        List<OrderItem> orderItemList = orderService.getOrderItemList(order.getId());

        Map<String, Object> result = new HashMap<>();
        result.put("order", order);
        result.put("orderItems", orderItemList);

        return CommonResult.success(result);
    }

    /**
     * 创建订单
     */
    @PostMapping
    public CommonResult<Order> createOrder(@RequestBody @Valid OrderCreateParam param) {
        Long userId = getCurrentUserId();
        try {
            Order order = orderService.createOrder(param, userId);
            return CommonResult.success(order);
        } catch (IllegalArgumentException e) {
            return CommonResult.failed(e.getMessage());
        } catch (Exception e) {
            return CommonResult.failed("创建订单失败：" + e.getMessage());
        }
    }

    /**
     * 取消订单
     */
    @PostMapping("/{orderNo}/cancel")
    public CommonResult<String> cancelOrder(@PathVariable String orderNo) {
        Long userId = getCurrentUserId();
        boolean success = orderService.cancelOrder(orderNo, userId);

        if (success) {
            return CommonResult.success("取消订单成功");
        } else {
            return CommonResult.failed("取消订单失败，订单不存在或状态不正确");
        }
    }

    /**
     * 确认收货
     */
    @PostMapping("/{orderNo}/receive")
    public CommonResult<String> confirmReceive(@PathVariable String orderNo) {
        Long userId = getCurrentUserId();

        // 查询订单
        Order order = orderService.getOrderDetail(orderNo, userId);
        if (order == null) {
            return CommonResult.notFound("订单不存在");
        }

        // 检查订单状态是否为待收货(2)
        if (order.getStatus() != 2) {
            return CommonResult.failed("只有待收货状态的订单才能确认收货");
        }

        // 更新订单状态为已完成(3)
        boolean success = orderService.updateOrderStatus(orderNo, 3);

        if (success) {
            return CommonResult.success("确认收货成功");
        } else {
            return CommonResult.failed("确认收货失败");
        }
    }

    /**
     * 获取当前登录用户ID
     */
    private Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User user = userService.getUserByUsername(username);
        return user.getId();
    }
}
